#include "hi_wifi_api.h"
#include "netifapi.h"

#include <string.h>
#include <stdio.h>

#include "wifi.h"

/** 开启WiFi **/
void Network_wifi_open(uint8_t *sta_name)
{
    uint32_t  ret;
    //STA名称为17Bytes
    uint32_t  len = 17;

    //开启STA模式获取STA名称
    ret = hi_wifi_sta_start(sta_name, &len);
    if (ret != 0) {
        //wifi打开失败
        printf("sta open failed!!!\r\n");
        return;
    }
    //wifi打开成功
    printf("sta open succeed!!!\r\n");

    ret = hi_wifi_sta_scan();  //扫描附件的WiFi
    if (ret != 0) {
        //wifi扫描失败
        printf("WiFi scan failed!!!\r\n");
        return ;
    }
    //wifi扫描失败
    printf("WiFi scan succeed!!!\r\n");

    usleep(5*1000*1000);  //等待扫描完成
}

/** wifi连接函数 **/
void Network_wifi_connect(uint8_t *wifi_name, uint8_t *wifi_password)
{
    uint32_t ret;
    //WiFi配置结构体
    hi_wifi_assoc_request assoc_req = {0};

    //设置要连接的WiFi的名字
    strcpy(assoc_req.ssid, wifi_name);
    //热点密码
    strcpy(assoc_req.key, wifi_password);
    //热点加密方式
    assoc_req.auth = HI_WIFI_SECURITY_WPA2PSK;

    /* 连接至热点 */
    ret = hi_wifi_sta_connect(&assoc_req);
    if (ret != 0) {
        //wifi连接失败
        printf("WiFi connection failed!!!\r\n");
    }
    //wifi连接成功
    printf("WiFi connection succeed!!!\r\n");
}

/** 获取网络 **/
void Network_wifi_gain(uint8_t *sta_name)
{
    uint32_t ret;
    //定义结构体保存网卡信息
    struct netif *g_lwip_netif = NULL;

    //根据STA名称获取网卡信息
    g_lwip_netif = netifapi_netif_find(sta_name);
    //根据网卡信息开启DHCP，自动获取IP
    ret = netifapi_dhcp_start(g_lwip_netif);
    if (ret != 0) {
        //wifi获取网络失败
        printf("WiFi gain failed!!!\r\n");
        return ;
    }
    //wifi获取网络失败
    printf("WiFi gain succeed!!!\r\n");
}

